from django.db import transaction
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import Upload, SystemLog, Option
from apps.system.serializers import OptionDictSerializer
from .serializers import ProductSerializers, ProductParameterSerializer, RelateProductSerialzier
from .models import Product, ProductParameter
from .filters import ProductFilter


# Create your views here.

class ProductDictViewSet(APIView):
    permission_classes = [permissions.IsAdminUser]

    # 返回产品的字典参数
    def get(self, request):
        ret = {
            'status': Product.STATUS_JSON,
            'category': OptionDictSerializer(Option.objects.filter(type=Option.PRODUCT_CATEGORY, enable=True),
                                             many=True).data
        }
        return response_ok(ret)


class ProductViewSet(CustomModelViewSet):
    '''产品'''
    permission_classes = [permissions.IsAdminUser]
    queryset = Product.objects.filter(delete=False)
    serializer_class = ProductSerializers

    def filter_queryset(self, queryset):
        f = ProductFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    return response_ok(instance.id)
        except Exception as e:
            return response_error(str(e))

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
                SystemLog.objects.add_log(self.request.user, SystemLog.DELETE, '删除产品product(id=%s)信息' % instance.id)
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_image(self, request, pk):
        product = Product.get_instance_by_id(pk)
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(file, 'product')
                product.images.add(upload)
                return response_ok()
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def add_image(self, request, pk):
        # 产品图片
        try:
            product = Product.get_instance_by_id(pk)
            image_id = request.data.get('imageId')
            upload = Upload.get_instance_by_id(image_id)
            with transaction.atomic():
                product.images.add(upload)
            return response_ok()
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def add_detail_image(self, request, pk):
        # 产品详情图片
        try:
            product = Product.get_instance_by_id(pk)
            image_id = request.data.get('imageId')
            upload = Upload.get_instance_by_id(image_id)
            with transaction.atomic():
                product.details_images.add(upload)
            return response_ok()
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def add_parameters(self, request, pk):
        try:
            product = Product.get_instance_by_id(pk)
            parameter = request.data.get('parameter')
            value = request.data.get('value')
            if parameter is None or value is None:
                return response_error('parameter或value为空。')
            with transaction.atomic():
                product_parameter = ProductParameter.objects.create(parameter=parameter, value=value)
                product.parameters.add(product_parameter)
            return response_ok(product_parameter.id)
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def del_parameters(self, request, pk):
        try:
            product = Product.get_instance_by_id(pk)
            parameter_id = request.data.get('parameterId')
            product_parameter = ProductParameter.get_instance_by_id(parameter_id)
            with transaction.atomic():
                product.parameters.remove(product_parameter)
                product_parameter.delete()
            return response_ok()
        except Exception as e:
            return response_error(str(e))


class ProductParameterViewSet(CustomModelViewSet):
    '''产品参数'''
    permission_classes = [permissions.IsAdminUser]
    queryset = ProductParameter.objects.filter()
    serializer_class = ProductParameterSerializer


class RelateProductViewSet(ListAPIView):
    queryset = Product.objects.filter(delete=False, status=Product.SHELVE)
    serializer_class = RelateProductSerialzier
